# # A、B、C类IP地址
# # ipA = r'(^([1-9]|[1-9]\d|1[0-2][0-6])\.(([0-9]|[1-9]\d|1\d\d|2[0-5][0-5])\.){2}([0-9]|[1-9]\d|1\d\d|2[0-5][0-5])$)'
# # ipB = r'(^(12[8-9]|1[3-8][0-9]|19[0-1])\.(([0-9]|[1-9]\d|1\d\d|2[0-5][0-5])\.){2}([0-9]|[1-9]\d|1\d\d|2[0-5][0-5])$)'
# # ipC = r'(^(19[2-9]|2[0-1][0-9]|22[0-3])\.(([0-9]|[1-9]\d|1\d\d|2[0-5][0-5])\.){2}([0-9]|[1-9]\d|1\d\d|2[0-5][0-5])$)'
#
# import IPy
# import re
# import json
#
# # 读取已用IP文件中的数据
# def readIP():
#   with open("已用IP.txt", "r", encoding='UTF-8') as f:
#     ip_list = json.load(f)
#     print(ip_list)
#     f.close()
#     return ip_list
# # 写入未用IP的数据到文件中
# def wirteIP(ip_list1):
#     with open("未用IP.txt", 'w+', encoding="GBK") as fp:
#         for i in range(0,len(ip_list1)):
#           fp.writelines(str(ip_list1[i]))
#           fp.write('\n')
#         fp.close()
#
# def main():
#     # 定义一个列表存储未使用的IP地址
#  ip_list1 = []
#  print(f"{'局域网存活IP验证程序':=^50}")
#  try:
#     input1 = input("请输入你的网段、子网掩码：")
#     raise ValueError
#     # 获取已用IP文件里面的IP列表
#     ip_list2 = readIP()
#     # 注意使用IPy包创建的对象的类型是IPy.IP 不是str类型
#     ips = IPy.IP(input1)
#     for ip in ips:
#         if str(ip) in ip_list2:
#             continue
#         else:
#             ip_list1.append(ip)
#     wirteIP(ip_list1)
#  except ValueError as V:
#     print("输入的不是IP地址！")
#
# main()

import subprocess
import IPy
import re
try:
    ips = input("请输入你要检测的网段：")
    if re.findall(r'\d{1,3}(\.\d{1,3}){3}/[0-9]+',ips):
      ip = IPy.IP(ips)
    else:
        raise ValueError
    for i in ip:
       return1 = subprocess.getoutput(f'ping -n 1 {i}')
       if "请求超时" in return1:
           print(f'{i} 可以使用')
           with open('未用IP.txt','a+',encoding='utf-8') as fp:
               fp.write(f'{i}\n')
               fp.close()
           continue
       else:
           print(f'{i} 不可使用')
           with open('已用IP.txt','a+',encoding='utf-8') as f:
               f.write(f'{i}\n')
               f.close()
except ValueError as V:
    print("输入的网段有误！")

